/**
 * 
 */
package kr.pe.johnkim.dayve.activity;

import java.io.IOException;
import java.util.List;

import kr.pe.johnkim.dayve.provider.DayveItemEvent;
import kr.pe.johnkim.dayve.provider.DayveLog;
import kr.pe.johnkim.dayve.rest.DayveCommonRest;
import kr.pe.johnkim.dayve.rest.DayveItemEventRest;
import kr.pe.johnkim.dayve.util.DayveCommon;

import org.json.JSONException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 아이템 이벤트 메모를 수정하는 클래스 이다.
 * 메모만 수정 가능 하다.
 * 
 * @author johnkim
 *
 */
public class DayveItemEventModifyView extends Activity {

	public static final String TAG = DayveItemEventModifyView.class.getSimpleName();
	
	private String DAYVE_ID = "";
	
	DayveItemEventRest dayveItemEventRest = new DayveItemEventRest();
	DayveCommonRest dayveCommonRest = new DayveCommonRest();
	DayveCommon dayveCommon = new DayveCommon();
	
	// 현재 시간.
	private String currentDate;
	
	ProgressBar progressBarItemEventModify;
	
	EditText edtTextItemEventComment;
	
	Button btnItemEventSave;
	
	TextView txtViewItemEventModifyNotification;
	
	// Item event comment 를 수정 한다.
	private static final int THREAD_UPDATE_ITEM_EVENT_COMMENT = 100;

	// 프로그레스 바를 출력 한다.
	private static final int THREAD_PROGRESS_BAR_VISIBLE = 101;

	// 프로그레스 바를 감춘다.
	private static final int THREAD_PROGRESS_BAR_INVISIBLE = 102;

	// Item event 업데이트 성공하면 토스트를 띄운다.
	private static final int THREAD_UPDATE_SUCCESS = 103;

	// Item event 업데이트 실패하면 오류발생 다이얼로그 창을 띄운다.
	private static final int THREAD_UPDATE_FAIL = 104;
	
	private String idMyHistoryItemEvents;
	private String comment;
	private String amount;
	private String openItemEventYn;
	private String favoriteYn;
	private String activateYn;
	private String modifyDate;
	private String myHistoryMembersId;
	private String myHistoryItemsIdMyHistoryItems;
	
	private String RESULT_UPDATE_ITEM_EVENT_COMMENT = "";

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.dayve_item_event_modify);
		
		// SharedPreferences 정보를 확인 한다.
		confirmNotification();
		
		Intent i = getIntent();
		
		idMyHistoryItemEvents = i.getStringExtra("idMyHistoryItemEvents");
		comment = i.getStringExtra("comment");
		amount = i.getStringExtra("amount");
		openItemEventYn = i.getStringExtra("openItemEventYn");
		favoriteYn = i.getStringExtra("favoriteYn");
		activateYn = i.getStringExtra("activateYn");
		modifyDate = i.getStringExtra("modifyDate");
		myHistoryMembersId = i.getStringExtra("myHistoryMembersId");
		myHistoryItemsIdMyHistoryItems = i.getStringExtra("myHistoryItemsIdMyHistoryItems");
		
		Log.i(TAG, "idMyHistoryItemEvents          : " + idMyHistoryItemEvents);
		Log.i(TAG, "comment                        : " + comment);
		Log.i(TAG, "amount                         : " + amount);
		Log.i(TAG, "openItemEventYn                : " + openItemEventYn);
		Log.i(TAG, "favoriteYn                     : " + favoriteYn);
		Log.i(TAG, "activateYn                     : " + activateYn);
		Log.i(TAG, "modifyDate                     : " + modifyDate);
		Log.i(TAG, "myHistoryMembersId             :  + myHistoryMembersId");
		Log.i(TAG, "myHistoryItemsIdMyHistoryItems : " + myHistoryItemsIdMyHistoryItems);
		
		progressBarItemEventModify = (ProgressBar)findViewById(R.id.progressBarItemEventModify);
		edtTextItemEventComment = (EditText)findViewById(R.id.edtTextItemEventComment);
		btnItemEventSave = (Button)findViewById(R.id.btnItemEventSave);
		txtViewItemEventModifyNotification = (TextView)findViewById(R.id.txtViewItemEventModifyNotification);
		
		progressBarItemEventModify.setVisibility(View.INVISIBLE);
		txtViewItemEventModifyNotification.setVisibility(View.INVISIBLE);
		
		edtTextItemEventComment.setText(comment);
		
		btnItemEventSave.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mHandler.sendMessage(mHandler.obtainMessage(THREAD_UPDATE_ITEM_EVENT_COMMENT));
			}
			
		});
	}
	
	/**
	 * SharedPreferences 정보를 확인 한다.
	 */
	public void confirmNotification() {
		String myPf = "kr.pe.johnkim.dayve.activity_preferences";
		SharedPreferences mSharedPreferences = getSharedPreferences(myPf, Activity.MODE_PRIVATE);
		
		// id 를 가져 온다.
		DAYVE_ID = mSharedPreferences.getString("dayve_id", "");
		
		// 현재 시간을 가져 온다.
		currentDate = dayveCommon.getCurrentDate();
	}
	
	/**
	 * Handler 를 등록 한다.
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			// Item event comment 를 수정 한다.
			case THREAD_UPDATE_ITEM_EVENT_COMMENT : 
				threadUpdateItemEvent();
				break;
			// 프로그레스 바를 감춘다.
			case THREAD_PROGRESS_BAR_INVISIBLE : 
				progressBarItemEventModify.setVisibility(View.INVISIBLE);
				txtViewItemEventModifyNotification.setVisibility(View.INVISIBLE);
				break;
			// 프로그레스 바를 출력 한다.
			case THREAD_PROGRESS_BAR_VISIBLE : 
				progressBarItemEventModify.setVisibility(View.VISIBLE);
				txtViewItemEventModifyNotification.setVisibility(View.VISIBLE);
				break;
			// Item event comment 수정에 성공하면 toast 를 띄운다.
			case THREAD_UPDATE_SUCCESS : 
				showUpdateItemEventCommentToast();
				break;
			// Item event comment 수정에 실패하면 dialog 를 띄운다.
			case THREAD_UPDATE_FAIL : 
				showDialogUpdateItemEventCommentFail();
				break;
			}
		}
	};

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// main thread 에서 child thread 를 호출 한다.
		Thread thread = new Thread(null, insertLogBackgroundThreadProcessing, "Background_insertLog");
		thread.start();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	/**
	 * Item event comment 를 수정 한다.
	 */
	private void threadUpdateItemEvent() {
		Log.i(TAG, "threadUpdateItemEvent");
		// 프로그레스 바를 출력 한다.
		mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_VISIBLE));

		Thread thread = new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				updateItemEvent();
			}

		});

		thread.start();
	}
	
	/**
	 * Item event comment 를 수정 한다.
	 */
	private void updateItemEvent() {
		Log.i(TAG, "updateItemEvent");
		
		DayveItemEvent parameterItemEvent = new DayveItemEvent();
		
		parameterItemEvent.setIdMyHistoryItemEvents(idMyHistoryItemEvents);
		parameterItemEvent.setComment(edtTextItemEventComment.getText().toString().trim());
		parameterItemEvent.setAmount(amount);
		parameterItemEvent.setOpenItemEventYn(openItemEventYn);
		parameterItemEvent.setFavoriteYn(favoriteYn);
		parameterItemEvent.setActivateYn(activateYn);
		parameterItemEvent.setModifyDate(currentDate);
		parameterItemEvent.setMyHistoryMembersId(myHistoryMembersId);
		parameterItemEvent.setMyHistoryItemsIdMyHistoryItems(myHistoryItemsIdMyHistoryItems);
		
		try {
			RESULT_UPDATE_ITEM_EVENT_COMMENT = dayveItemEventRest.updateItemEvent(parameterItemEvent).getResult();
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
		}
		
		if(("SUCCESS").equals(RESULT_UPDATE_ITEM_EVENT_COMMENT)) {
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_UPDATE_SUCCESS));
			
//			DayveItemView.RESULT_ITEM_REGISTER = "SUCCESS";
//			DayveCategoryAnalysisView.RESULT_ITEM_REGISTER = "SUCCESS";
//			DayveCategoryView.RESULT_CATEGORY_REGISTER = "SUCCESS";
//			DayveFavoriteView.RESULT_CATEGORY_REGISTER = "SUCCESS";
//			
//			DayveCategoryView.ACTIVITY_RESULT = "";
			
			DayveItemAmountView.RESULT_UPDATE_ITEM_EVENT = "SUCCESS";
			
			Intent i = new Intent();
			setResult(RESULT_OK, i);
			
			finish();
		} else {
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_UPDATE_FAIL));
		}
	}

	/**
	 * Item event comment 업데이트 성공 Toast 를 띄운다.
	 */
	private void showUpdateItemEventCommentToast() {
		CharSequence text = getResources().getString(R.string.item_event_modify_success_update);
		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}
	
	/**
	 * Item event comment 업데이트 실패 다이얼로그 창을 띄운다.
	 */
	private void showDialogUpdateItemEventCommentFail() {
		Log.e(TAG, "showDialogRegisterCategoryFail");
		
		new AlertDialog.Builder(DayveItemEventModifyView.this)
		.setTitle(getResources().getString(R.string.item_event_modify_fail_update_title))
		.setMessage(
				getResources().getString(R.string.item_event_modify_fail_update_message_01) + 
				"\n" + 
				getResources().getString(R.string.item_event_modify_fail_update_message_02)
				)
		.setPositiveButton(getResources().getString(R.string.item_event_modify_fail_update_button_ok), 
			new DialogInterface.OnClickListener() {
				
//				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			}).show();
	}
	
	/* 최상위 프로세스가 아닐 경우 프로세스를 종료 한다.
	 * 
	 * => Home Key 를 눌렀을때 프로세스를 종료 한다.
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if(!isForegrdound()) {
			DayveItemAmountView.activity.finish();
			DayveItemView.activity.finish();
			System.exit(0);
		}
	}
	
	/**
	 * 현재 프로세스가 최상위로 실행중인지 검사 한다.
	 * 
	 * true : 최상위
	 * 
	 * @return
	 */
	public boolean isForegrdound() {
	    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> list = am.getRunningTasks(1);
	    ComponentName cn = list.get(0).topActivity;
	    String name = cn.getPackageName();
	     
	    return name.indexOf(getPackageName()) > -1;
	}
	
	/**
	 * 로그를 저장 한다.
	 */
	private void insertLog() {
		Log.i(TAG, "insertLog");
		
		DayveLog dayveLog = new DayveLog();
		
		dayveLog.setId(DAYVE_ID);
		dayveLog.setViewName(TAG);
		dayveLog.setAccessDate(currentDate);
		
		try {
			dayveCommonRest.registerLog(dayveLog);
			Log.i(TAG, "Success to insert log.");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		}
	}
	
	/**
	 * 로그 저장은 UI 와 관계 없기 때문에 background thread 로 구현 함 : child thread
	 */
	private Runnable insertLogBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
			// TODO Auto-generated method stub
			insertLog();
		}
	};
}
